package com.example.confessdemo.slice;

import com.example.confessdemo.ResourceTable;
import com.huawei.agconnect.appmessaging.AGConnectAppMessaging;
import com.huawei.agconnect.appmessaging.AGConnectAppMessagingOnDisplayListener;
import com.huawei.agconnect.appmessaging.model.AppMessage;
import com.huawei.agconnect.common.api.AGCInstanceID;
import com.huawei.agconnect.remoteconfig.AGConnectConfig;
import com.huawei.agconnect.remoteconfig.ConfigValues;
import com.huawei.hmf.tasks.OnSuccessListener;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Image;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;

public class MainAbilitySlice extends AbilitySlice {
    private AGConnectAppMessaging appMessaging;

    long intervalTime=0;
    private String flag="new";

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        //获取AAID，可以在下一句下断点查看，并复制到AppGallery Connect中测试用户AAID中
        String aaid = AGCInstanceID.getInstance().getId();
        //显示应用内消息
        displayMessage();
        replaceConfig();
    }

    private void replaceConfig() {
        AGConnectConfig agConnectConfig=AGConnectConfig.getInstance();
        agConnectConfig.fetch(intervalTime).addOnSuccessListener(new OnSuccessListener<ConfigValues>() {
            @Override
            public void onSuccess(ConfigValues configValues) {
                agConnectConfig.apply(configValues);
                String value=agConnectConfig.getValueAsString("replace_image");

                Image image=findComponentById(ResourceTable.Id_image_banner);
                if (value.equals(flag)){
                    image.setPixelMap(ResourceTable.Media_new_love);
                }
                else{
                    image.setPixelMap(ResourceTable.Media_love);
                }
            }
        });
    }

    //配置应用内消息
    private void displayMessage() {
        //调用AGConnectAppMessaging.getInstance初始化AGConnectAppMessaging实例
        appMessaging = AGConnectAppMessaging.getInstance();
        // 设置是否允许同步AGC服务端数据
        appMessaging.setFetchMessageEnable(true);
        // 设置是否允许展示消息
        appMessaging.setDisplayEnable(true);
        // 消息展示监听器
        appMessaging.addOnDisplayListener(new AGConnectAppMessagingOnDisplayListener() {
            public void onMessageDisplay(AppMessage param1AppMessage) {
                new ToastDialog(getContext())
                        .setDuration(2000)
                        .setAlignment(LayoutAlignment.CENTER)
                        .setText("已经显示了5.20告白消息")
                        .show();
            }
        });
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {

    }
}